package com.msds.parent.shiro;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.junit.Test;

public class MyRealm extends AuthorizingRealm
{

	/* 用于授权 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0)
	{
		System.out.println("===用于授权=====doGetAuthorizationInfo=======");
		/*为用户授权*/
		/*拿到用户名*/
		String username=arg0.getPrimaryPrincipal()+"";
		/*权限集合*/
		List<String> permissList=new ArrayList<String>();
		permissList.add("users:insert");
		permissList.add("users:delete");
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		simpleAuthorizationInfo.addRole("role1");
		
		/*将权限放到SimpleAuthorizationInfo 中*/
		for (Iterator iterator = permissList.iterator(); iterator.hasNext();)
		{
			String string = (String) iterator.next();
			simpleAuthorizationInfo.addStringPermission(string);
		}
		return simpleAuthorizationInfo;
	}
	
	/* 用于验证       没有采用任何的加密方式 */
	/*@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException
	{
		System.out.println("===用于验证=====doGetAuthenticationInfo=======");
		 写上从数据库中查询 
		String username = "zhangsan";
		String pass = "111111";
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username, pass,
				this.getName());
		return simpleAuthenticationInfo;
	}*/
	

	/*加密*/
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException
	{
		System.out.println("===用于验证=====doGetAuthenticationInfo=======");
		String username="zhangsan";
		String pass="96e79218965eb72c92a549dd5a330112";
		/*采用加盐，盐值一定一致*/
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(username, pass, ByteSource.Util.bytes("test"),this.getName());
		return simpleAuthenticationInfo;
	}
	@Test
	 public void TestPass(){
         /*加密*/
		 String salt="zhaoxiaojing";
		 /*正常加密的MD5*/
		 String pass="111111";
		 String jiaMiPass=new Md5Hash(pass).toString();
		 System.out.println("加密："+jiaMiPass);
		 
		 /*加盐*/
		 jiaMiPass=new Md5Hash(pass,salt)+"";
		 System.out.println("加密（加盐）："+jiaMiPass);
		 
		 /*加2次盐*/
		 jiaMiPass=new Md5Hash(pass, salt, 2)+"";
		 System.out.println("加密（加盐2）："+jiaMiPass);
	 }

}
